//
//  ServicePanelSensorContact.swift
//  home
//
//  Created by Yun Zeng on 2019/9/26.
//  Copyright © 2019 Yun Zeng. All rights reserved.
//

import UIKit

class ServicePanelSensorContact: ServicePanelBase {
    
    var contact: ServiceSensorContact
    
    init(contact: ServiceSensorContact) {
        self.contact = contact
        super.init(service: contact.service)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var notifySwitchLabel: ServiceNotifySwitchLabel = {
        let label = ServiceNotifySwitchLabel(frame: .zero)
        return label
    } ()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.customBar.title = self.contact.room + self.contact.name
        self.customBar.subtitle = self.contact.desc
        self.view.backgroundColor = UIColor(hex: "d7d7d7")
        
        self.view.addSubview(self.notifySwitchLabel)
        notifySwitchLabel.backgroundColor = UIColor(hex: "EBEBEB")
         notifySwitchLabel.translatesAutoresizingMaskIntoConstraints = false
         notifySwitchLabel.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 15).isActive = true
         notifySwitchLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -15).isActive = true
         notifySwitchLabel.topAnchor.constraint(equalTo: self.customBar.bottomAnchor, constant: 19).isActive = true
        
        self.contact.contactStateChar.getHistoryLimit(max: 10, completionHandler: self.handleHistoryData)
    }
    
    
    // 处理获取的温度历史数据
    func handleHistoryData(message: CloudMessage?) -> Void {
        guard let data = message?.data else {
            return
        }
        
        guard let clogs = try? JSONDecoder().decode(CharactersiticLogs.self, from: data) else {
            return
        }

        let datas = self.getClassifiedData(clogs: clogs)
        for data in datas {
            print("\(data.dayDesc)")
            for record in data.records {
                print("\t \(record.time)\t\(record.desc)")
            }
        }
        
        DispatchQueue.main.async {
            let stackView = UIStackView()
            stackView.axis = .vertical
            stackView.distribution = .equalSpacing
            stackView.alignment = .center
            stackView.translatesAutoresizingMaskIntoConstraints = false
            self.view.addSubview(stackView)
            stackView.translatesAutoresizingMaskIntoConstraints = false
            stackView.topAnchor.constraint(equalTo: self.notifySwitchLabel.bottomAnchor, constant: 20).isActive = true
            stackView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 15).isActive = true
            stackView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -15).isActive = true
            stackView.customize(backgroundColor: UIColor(hex: "EBEBEB"), radiusSize: 12)

            let topSpace = UIView()
            topSpace.translatesAutoresizingMaskIntoConstraints = false
            topSpace.heightAnchor.constraint(equalToConstant: 5).isActive = true
            stackView.addArrangedSubview(topSpace)

            for logs in datas {
                let view = ContactSensorDayLogView(logs: logs)
                view.translatesAutoresizingMaskIntoConstraints = false
                stackView.addArrangedSubview(view)
                view.leadingAnchor.constraint(equalTo: stackView.leadingAnchor, constant: 23).isActive = true
            }

            let bottomSpace = UIView()
            bottomSpace.translatesAutoresizingMaskIntoConstraints = false
            bottomSpace.heightAnchor.constraint(equalToConstant: 50).isActive = true
            stackView.addArrangedSubview(bottomSpace)
        }
        
    }
}


// 推送开关通知标签
class ServiceNotifySwitchLabel: UIView {
    
    private lazy var title: UILabel = {
        let label = UILabel()
        let attributes: [NSAttributedString.Key : Any] = [
        NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.regular),
        NSAttributedString.Key.kern: -0.41,
        NSAttributedString.Key.foregroundColor: UIColor.black]
        label.textAlignment = .left
        label.autoresizingMask = .flexibleWidth
        label.attributedText = NSAttributedString(string: "状态变化推送通知", attributes: attributes)
        return label
    } ()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = UIColor(hex: "F2F2F2")
        self.heightAnchor.constraint(equalToConstant: 50).isActive = true
        self.layer.cornerRadius = 12
        
        self.addSubview(self.title)
        title.translatesAutoresizingMaskIntoConstraints = false
        title.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 15).isActive = true
        title.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
        
        let sw = UISwitch()
        self.addSubview(sw)
        sw.translatesAutoresizingMaskIntoConstraints = false
        sw.heightAnchor.constraint(equalToConstant: 32).isActive = true
        sw.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -15).isActive = true
        sw.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
        sw.isOn = true
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK: -历史记录标签
fileprivate class ContactSensorDayLogView: UIView {

    init(logs: LogClassification) {
        super.init(frame: .zero)

        let title = UILabel()
        let attributes: [NSAttributedString.Key : Any] = [
            NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium),
            NSAttributedString.Key.kern: 0.38,
            NSAttributedString.Key.foregroundColor: UIColor.black]
        title.textAlignment = .left
        title.autoresizingMask = .flexibleWidth
        title.attributedText = NSAttributedString(string: logs.dayDesc, attributes: attributes)

        self.addSubview(title)
        title.translatesAutoresizingMaskIntoConstraints = false
        title.topAnchor.constraint(equalTo: self.topAnchor, constant: 10).isActive = true
        title.heightAnchor.constraint(equalToConstant: 40).isActive = true
        title.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true

        self.translatesAutoresizingMaskIntoConstraints = false
        self.heightAnchor.constraint(equalToConstant: CGFloat(40 + 10 + logs.records.count * 32)).isActive = true

        // 竖线
        if logs.records.count > 1 {
            let line = UIView(frame: CGRect(x: 37.0, y: 50.0 + 16.0, width: 1.0, height: Double(logs.records.count * 32 - 34)))
            line.backgroundColor = UIColor(hex: "979797")
            self.addSubview(line)
        }

        for (i, v) in logs.records.enumerated() {
            let label = UILabel()
            let attributes: [NSAttributedString.Key : Any] = [
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.regular),
                NSAttributedString.Key.kern: 0.38,
                NSAttributedString.Key.foregroundColor: UIColor(red: 0, green: 0, blue: 0, alpha: 0.7)]
            label.textAlignment = .left
            label.autoresizingMask = .flexibleWidth
            label.attributedText = NSAttributedString(string: v.time + "   " + v.desc, attributes: attributes)

            self.addSubview(label)
            label.translatesAutoresizingMaskIntoConstraints = false
            label.heightAnchor.constraint(equalToConstant: 32).isActive = true
            label.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 55).isActive = true
            label.topAnchor.constraint(equalTo: title.bottomAnchor, constant: CGFloat(i * 32)).isActive = true

            // 竖线上的点
            let dot = UIView(frame: CGRect(x: 35, y: 50 + 14 + i * 32, width: 5, height: 5))
            dot.layer.cornerRadius = 2.5
            dot.backgroundColor = UIColor(hex: "979797")
            self.addSubview(dot)
        }

    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK: - 返回数据
struct CharactersiticLogs: Codable {
    var aid: String
    var sid: Int
    var cid: Int
    var before: String?
    var after: String?
    var limits: Int?
    struct CharacteristicLog: Codable {
        var time: String
        var value: AnyJSONType
    }
    var logs: [CharacteristicLog]
}

// MARK: - 数据分类
class LogClassification {
    var daysAgo: Int
    var dayDesc: String
    struct Record {
        var time: String
        var desc: String
    }
    var records = [Record]()

    init(daysAgo: Int, dayDesc: String) {
        self.daysAgo = daysAgo
        self.dayDesc = dayDesc
    }
}


// MARK: -获取分类的数据
extension ServicePanelSensorContact {
    func getClassifiedData(clogs: CharactersiticLogs) -> [LogClassification] {
        var logs = [LogClassification]()
        let now = Date()
        for v in clogs.logs {
            let date = v.time.toDate()
            
            let start = "2019-01-01 00:00:00".toDate()
            
            let components = Calendar.current.dateComponents(in: .current, from: date)
            let daysAgo = Int(now.timeIntervalSince(start) / (24 * 60 * 60)) - Int(date.timeIntervalSince(start) / (24 * 60 * 60))
            
            var dateDesc = ""
            switch daysAgo {
            case 0:
                dateDesc += "今天"
            case 1:
                dateDesc += "昨天"
            case 2:
                dateDesc += "前天"
            case 3...:
                dateDesc += String(format: "%d天前", daysAgo)
            default:
                break
            }
            let weeks = ["日", "一", "二",  "三",  "四",  "五",  "六"]
            dateDesc += (" 星期" + weeks[components.weekday! - 1])

            var timeDesc = ""
            switch (components.hour!) {
            case 0 ..< 6:
                timeDesc += "凌晨 " + String(format: "%d:%02d", components.hour!, components.minute!)
            case 6 ..< 12:
                timeDesc += "上午 " + String(format: "%d:%02d", components.hour!, components.minute!)
            case 12:
                timeDesc += "中午 " + String(format: "%d:%02d", components.hour!, components.minute!)
            case 13 ..< 18:
                timeDesc += "下午 " + String(format: "%d:%02d", components.hour! - 12, components.minute!)
            case 18 ..< 24:
                timeDesc += "傍晚 " + String(format: "%d:%02d", components.hour! - 12, components.minute!)
            default:
                break
            }

            var valueDesc = ""
            if v.value.toValueInt() == 1 {
                valueDesc = "大门关了"
            } else {
                valueDesc = "大门开了"
            }

            if  let last = logs.last, last.daysAgo == daysAgo {
                last.records.append(LogClassification.Record(time: timeDesc, desc: valueDesc))
            } else {
                let log = LogClassification(daysAgo: daysAgo, dayDesc: dateDesc)
                log.records.append(LogClassification.Record(time: timeDesc, desc: valueDesc))
                logs.append(log)
            }
        }
        return logs
    }
}
